package com.efounder.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ConvertUtil {

	private static XStream stream;
	
	public static Map<String, String> jsonString2Map(String jsonString){
		String sb = jsonString.substring(2, jsonString.length()-2);
		String[] name =  sb.split("\\\",\\\"");
		String[] nn =null;
		Map<String, String> map = new HashMap<String, String>();
		for(int i= 0;i<name.length; i++){
			nn = name[i].split("\\\":\\\"");
			map.put(nn[0], nn[1]);			
		}
		return map;
	}

	public static String map2JsonString(Map<String, String> map){
//		stream = new XStream(new JsonHierarchicalStreamDriver());
		//		String res = stream.toXML(map);
		//		return res;
		String jsonStr = "{"; 
		Set<?> keySet = map.keySet(); 
		for (Object key : keySet) { 
			jsonStr += "\""+key+"\":\""+map.get(key)+"\",";      
		} 
		jsonStr = jsonStr.substring(0,jsonStr.length()-1); 
		jsonStr += "}"; 
		return jsonStr;
	}

	public static String map2Xml(Map<String, String> map){
		stream = new XStream();
		String res = stream.toXML(map);
		return res;
	}

	public static Map<String, String> xml2Map(String xml){
		stream = new XStream(new DomDriver());
		Map<String, String> map = (Map<String, String>)stream.fromXML(xml);
		return map;
	}
	
	public static String bean2XML(Object object){
		stream = new XStream();
		String res = stream.toXML(object);
		return res;
	}
	
	public static Object xml2Bean(String xml){
		stream = new XStream();
		Object obj = stream.fromXML(xml);
		return obj;
	}
}
